package com.itheima.dao;

import com.github.pagehelper.Page;
import com.itheima.pojo.Menu;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 菜单 持久层接口
 */
public interface MenuDao {

    /**
     * 查询所有菜单  一对多查询所有子菜单
     *
     * @return List<Menu> 菜单集合
     */
    @Select("select * from t_menu where level=1 ")
    @Results({
            //主键 id = true
            @Result(property = "id", column = "id", id = true),
            //集合多对一 ,不能用列来表示column = "children", 一对一就用one
            //select * from t_menu where parentMenuId=id   column = "id" 相当于把id给他了
            @Result(property = "children", column = "id", many = @Many(select = "findChildrenById")),
    })
    List<Menu> findAll();

    /**
     * 根据父菜单id查询所有子菜单
     *
     * @param parentMenuId 父菜单id
     * @return List<Menu>子菜单集合
     */
    @Select("select * from t_menu where parentMenuId=#{parentMenuId}")
    List<Menu> findChildrenById(Integer parentMenuId);

    /**
     * 分页查询
     *
     * @param queryString 查询条件
     * @return 菜单集合
     */
    @Select("<script> select * from t_menu <if test=\" value != null and value != '' \">where name like \"%\"#{value}\"%\" </if></script>")
    Page<Menu> findPage(String queryString);

    /**
     * 添加菜单
     *
     * @param menu 菜单
     */
    @Insert("insert into t_menu (name,linkUrl,path,priority,icon,description,parentMenuId) values(#{name},#{linkUrl},#{path},#{priority},#{icon},#{description},#{parentMenuId}) ")
    void add(Menu menu);

    /**
     * 根据id查询菜单
     *
     * @param id 菜单id
     * @return 菜单
     */
    @Select("select * from t_menu where id=#{id}")
    Menu findById(Integer id);

    /**
     * 编辑菜单
     *
     * @param menu 菜单
     */
    @Update("update t_menu set name=#{name},linkUrl=#{linkUrl},path=#{path},priority=#{priority},icon=#{icon},description=#{description},parentMenuId=#{parentMenuId} where id=#{id} ")
    void edit(Menu menu);

    /**
     * 根据id删除菜单
     *
     * @param id 菜单id
     */
    @Delete("delete from t_menu where id=#{id}")
    void delete(Integer id);

    /**
     * 根据用户名查询拥有的菜单
     *
     * @param username 用户名
     * @return List<Menu>菜单集合
     */
    @Select(" select  m.*  from t_user  u, t_user_role ur  , t_role_menu rm , t_menu m where u.id = ur.role_id  and  ur.role_id=rm.role_id  \n" +
            "and  rm.menu_id=m.id  and  m.parentMenuId is null  and u.username=#{username} ")
    @Results({
            //主键 id = true
            @Result(property = "id", column = "id", id = true),
            //集合多对一 ,不能用列来表示column = "children", 一对一就用one
            //select * from t_menu where parentMenuId=id   column = "id" 相当于把id给他了
            @Result(property = "children", column = "id", many = @Many(select = "findChildrenById")),
    })
    List<Menu> loadMenu(String username);

}
